// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using Microsoft.Practices.Prism.StoreApps;
using ValidationQuickStart.Models;

namespace ValidationQuickStart.ViewModels
{
    //This QuickStart is documented at http://go.microsoft.com/fwlink/?LinkID=288827&clcid=0x409

    public class UserInfoViewModel : ViewModel
    {
        private UserInfo _userInfo;
        private DogInfo _dogInfo;
        private ReadOnlyCollection<string> _allErrors;

        public UserInfoViewModel()
            : this(new UserInfo(), new DogInfo())
        {
        }

        public UserInfoViewModel(UserInfo userInfo, DogInfo dogInfo)
        {
            _userInfo = userInfo;
            if (_userInfo != null)
            {
                _userInfo.ErrorsChanged += OnErrorsChanged;
            }

            _dogInfo = dogInfo;
            if (_dogInfo != null)
                _dogInfo.ErrorsChanged += OnErrorsChanged;

            _allErrors = BindableValidator.EmptyErrorsCollection;
            ValidateCommand = new DelegateCommand(Validate);
        }

        public UserInfo UserInfo
        {
            get { return _userInfo; }
            set { SetProperty(ref _userInfo, value); }
        }

        public DogInfo DogInfo
        {
            get { return _dogInfo; }
            set { SetProperty(ref _dogInfo, value); }
        }

        public ReadOnlyCollection<string> AllErrors
        {
            get { return _allErrors; }
            private set { SetProperty(ref _allErrors, value); }
        }

        public ICommand ValidateCommand { get; set; }

        private void Validate()
        {
            _userInfo.ValidateProperties();
            _dogInfo.ValidateProperties();
        }

        private void OnErrorsChanged(object sender, DataErrorsChangedEventArgs e)
        {
            var tempErrors = _userInfo.GetAllErrors().Values.SelectMany(c => c).ToList();
            tempErrors.AddRange(_dogInfo.GetAllErrors().Values.SelectMany(d => d).ToList());

            AllErrors = new ReadOnlyCollection<string>(tempErrors);
        }
    }
}
